package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.OSSProperties;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UploadService {

    // 文件上传的路径
    private static final String imgPath = "D:\\leyou123\\software\\nginx-leyou\\html\\brand-img";
    // 图片访问的url
    private static final String imgURL = "http://image.leyou.com/brand-img/";

    // 定义允许的mime类型
    private static final List UPLOAD_MIME_TYPE = Arrays.asList("image/jpeg","image/png");

    public String uploadImage(MultipartFile file) {
        // 判断图片的类型
        if(!UPLOAD_MIME_TYPE.contains(file.getContentType())){
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        BufferedImage read = null;
        try {
            // 验证是否是图片:  如果这个方法返回的有值代表这个是图片，返回为空或者异常都代表不是图片
            read = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        // 判断空
        if(read == null){
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        // 文件目录
        File imagePath = new File(imgPath);
        // 文件名称
        String imgName = UUID.randomUUID()+file.getOriginalFilename();
        // 直接把文件传输
        try {
            file.transferTo(new File(imagePath, imgName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        // 返回的图片的路径
        return imgURL+imgName;
    }


    //注入客户端
    @Autowired
    private OSS client;

    @Autowired
    private OSSProperties prop;

    /**
     * 获取OSS上传签名
     * @return
     */
    public Map<String,Object> signature() {
        try {
            long expireTime = prop.getExpireTime();  // 从配置文件获取过期时间
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());// 上传文件大小
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir()); // 上传所在的目录

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            // 返回给前端的内容：  这里一定要和上传组件对应起来
            Map<String, Object> respMap = new LinkedHashMap<String, Object>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);

            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }
}
